package com.xzw.test.springcloud.contorller;

import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixThreadPoolKey;
import com.xzw.test.springcloud.command.MyHystrixCommand;
import com.xzw.test.springcloud.model.CommonResult;
import com.xzw.test.springcloud.service.HystrixService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.Random;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

@RestController
public class HystrixController {

    @Autowired
    private HystrixService hystrixService;

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/getPaymentById/{id}")
    public CommonResult getUser(@PathVariable("id") Long id) {
        return hystrixService.getPaymentById(id);
    }

    /*@GetMapping
    public String getUser() throws InterruptedException {
        System.out.println(new Date() + ">>>" );
        //让处理线程等待几秒钟
        int sleepTime = new Random().nextInt(3000);
        System.out.println("sleepTime:" + sleepTime);
        Thread.sleep(sleepTime);
        return "调用成功: =====";
    }*/


    @GetMapping("/getUser2")
    public void getUser2() throws ExecutionException, InterruptedException {
        //同步执行
       // MyHystrixCommand myHystrixCommand = new MyHystrixCommand(HystrixCommand.Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("gongj")), restTemplate,1L);
        MyHystrixCommand myHystrixCommand = new MyHystrixCommand(
                HystrixCommand.Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("gongj"))
                        .andCommandKey(HystrixCommandKey.Factory.asKey("gongjie"))
                        .andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey("gongjiePoolKey")), restTemplate,1L);
        String execute = (String) myHystrixCommand.execute(); //直接执行
        System.out.println(execute);
        //异步执行
        MyHystrixCommand myHystrixCommand2 = new MyHystrixCommand(HystrixCommand.Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("gongj")), restTemplate,2L);
        Future queue = myHystrixCommand2.queue();  //先入队，后执行
        //调用get 方法来获取结果
        String o = (String) queue.get();
        System.out.println(o);
    }

    @GetMapping("/getUser3")
    public void getUser3() throws ExecutionException, InterruptedException {
        //异步执行
        Future<String> name2 = hystrixService.getName2();
        //调用get方法来获取结果
        String o =  name2.get();

        System.out.println("o= "+o);
    }


}
